<!-- 提交社群订单 -->
<template>
  <div class="index-container order-index-container">
    <van-barrage v-model="defaultList">
      <div class="main-video" style="width: 100%; height: 150px"></div>
    </van-barrage>
    <div class="goods-detail-flock-box">
      <div>
        <van-image
          :src="formData.avatar"
          fit="cover"
          width="100"
          height="100"
          radius="8"
        />
        <div class="goods-detail-flock">
          <h3>{{ formData.name }}</h3>
          <p>{{ formData.description }}</p>
        </div>
      </div>
    </div>
    <div class="image-list">
      <van-row>
        <van-col span="24">
          <h3>群成员（{{ formData.flockNum }}人）</h3>
        </van-col>
      </van-row>
      <van-grid :column-num="5" :border="false">
        <van-grid-item v-for="item in userList" :key="item.id">
          <div class="grid-item-img">
            <van-image
              :src="item.avatar ? item.avatar : item.icon"
              fit="cover"
              radius="6"
            />
            <p>{{ item.username ? item.username : "  " }}</p>
          </div>
        </van-grid-item>
      </van-grid>
      <div class="image-list-item">
        <h3>群简介</h3>
        <p>{{ formData.summary }}</p>
      </div>
      <div class="image-list-item">
        <h3>常见问题</h3>
        <p>
          一旦付费，无论何种原因概不退款包括违规被踢出群的），请谨慎选择，看好在买。付费观看更能让社群形成正向循环，是社群内容质量的保障。
        </p>
        <p>付费后跳转，扫描二维码即可观看喔！</p>
        <div class="read">阅读：10W+</div>
        <div class="share-btn">
          <div class="share-item-left">
            <div class="share-item" @click="shareAction()">
              <van-icon name="share-o" />
              <span>分享</span>
            </div>
            <div class="share-item" @click="isLikesAction()">
              <van-icon name="star" color="#f00" v-if="isLikes" />
              <van-icon name="star-o" v-else />
              <span>收藏</span>
            </div>
          </div>
          <div class="share-item-right">
            <div class="share-item">
              <van-icon name="good-job-o" />
              <span>{{ formData.likes }}</span>
            </div>
            <div class="share-item">
              <van-icon name="star-o" />
              <span>{{ formData.favorites }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="comment-list">
      <h3>群友评论（精选）</h3>
      <div class="comment-list-main">
        <div
          class="comment-item"
          v-for="(item, index) in formData.comments"
          :key="item.id"
        >
          <div class="comment-item-left">
            <van-image
              :src="item.userAvatar"
              :radius="8"
              width="48px"
              height="48px"
            />
            <div class="comment-item-content">
              <h6>{{ item.commenter }}</h6>
              <p>{{ item.content }}</p>
            </div>
          </div>
          <div class="comment-item-right" @click="linkAction(item, index)">
            <van-icon
              name="good-job"
              color="#ee0a24"
              size="20"
              v-if="item.isLink"
            />
            <van-icon name="good-job-o" size="20" v-else />
            <span>{{ item.likes }}</span>
          </div>
        </div>
      </div>
    </div>
    <div class="default-browser" v-if="isWxPay">
      <img src="@/assets/image/img08.png" alt="" />
    </div>
    <div class="footer-box footer">
      <div class="submit-foote">
        <van-button
          type="primary"
          color="linear-gradient(to right, #ff6034, #ee0a24)"
          block
          :loading="isLoading"
          @click="payOrder"
          >限时 {{ formData.price }} （次日恢复{{
            formData.nextDayPrice
          }}）</van-button
        >
      </div>
    </div>
    <!-- <van-submit-bar :price="amount" button-text="提交订单" tip="寄送至：湖北 武汉 武昌, 吴先生" :loading="isLoading" -->
    <!-- <van-submit-bar
      :price="amount"
      button-text="立即支付"
      :loading="isLoading"
      tip="订单为线上产品，请谨慎购买"
      class="btn-color"
      @submit="payOrder"
    />-->
  </div>
</template>
<script setup>
import { computed, reactive, toRefs, ref, onMounted } from "vue";
import { appid, wwwUrl } from "@/utils/constant";
import { useRoute, useRouter } from "vue-router";
import { showToast } from "vant";
import {
  CreateGoodsOrder, // 新增订单
} from "@/api/goods/index.js";

import {
  GetFlockDetail, // 获取群详情
} from "@/api/common";

import {
  GetOrderInfoByTradeNo,
  GetOpenid,
  CreatePayOrder,
} from "@/api/mine/index.js";

import Icon10 from "@/assets/icon/10.jpg";
import Icon11 from "@/assets/icon/11.jpg";

const route = useRoute();
const router = useRouter();

const checked = ref("1");

const state = reactive({
  Img01: "",
  anchorType: [
    {
      id: 1,
      title: "vip永久更新",
      image: "",
      checked: true,
      money: 0.1,
      context: "元",
    },
  ],
  orderNumber: "", // 订单编号
  isOrder: false,
  isWeixin: false,
  formData: {
    name: "",
    description: "",
    avatar: "",
    members: [],
    comments: [],
    summary: "",
    views: 109982,
    favorites: 1863,
    likes: 6254,
    flockNum: 458,
    price: "",
    nextDayPrice: "",
  },
});

const { formData } = toRefs(state);

const userList = ref([
  {
    id: 11,
    icon: Icon11,
    username: "  ",
  },
  {
    id: 10,
    icon: Icon10,
    username: "  ",
  },
]);

const defaultList = ref([{ id: 100, text: "轻量" }]);

let isLoading = ref(false);
let setIntTime = null;
let orderNum = "";
let isPay = false;
let isWxPay = ref(false);

const initWeixinJSBridge = () => {
  if (typeof WeixinJSBridge === "object") {
  } else {
    // 微信JSBridge不存在，监听微信JSBridgeReady事件
    document.addEventListener("WeixinJSBridgeReady", () => {}, false);
  }
};

// 拉起微信支付
const onBridgeReady = (pay_info) => {
  console.log(WeixinJSBridge, "WeixinJSBridge222");
  if (WeixinJSBridge !== null) {
    WeixinJSBridge.invoke(
      "getBrandWCPayRequest",
      {
        appId: pay_info.appId, //appid
        timeStamp: pay_info.timeStamp, //时间戳，自1970年以来的秒数
        nonceStr: pay_info.nonceStr, //随机串
        package: pay_info.package,
        signType: pay_info.signType, //微信签名方式：
        paySign: pay_info.paySign, //微信签名
      },
      function (res) {
        console.log("====>: onBridgeReady -> res", res, pay_info);
        if (res.err_msg == "get_brand_wcpay_request:ok") {
          router.push({
            path: "/payResult",
            query: {
              out_trade_no: pay_info.out_trade_no,
            },
          });

          // 使用以上方式判断前端返回,微信团队郑重提示：
          //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
        } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
        } else {
        }
      }
    );
  } else {
    console.log("不是在微信app内");
  }
};

const payOrder = async () => {
  if (is_weixn()) {
    let params = {
      openid: localStorage.getItem("openid"),
      goodsId: route.query.goodsId,
      orderType: 3,
    };
    let { data } = await CreatePayOrder(params);
    console.log(params, "params", data);
    let pay_info = {
      appId: data.appId, //appid
      timeStamp: data.timeStamp, //时间戳，自1970年以来的秒数
      nonceStr: data.nonceStr, //随机串
      package: data.package,
      signType: data.signType, //微信签名方式：
      paySign: data.paySign, //微信签名
      out_trade_no: data.out_trade_no, //微信签名
    };
    onBridgeReady(pay_info);
  } else {
    alipay();
  }
  //
};

const alipay = async () => {
  orderNum = "";
  isPay = false;
  let paramsorder = {
    goodsId: route.query.goodsId,
    orderType: 3,
  };
  isLoading.value = true;
  let datares = await CreateGoodsOrder(paramsorder);
  let resData = datares.data;
  isLoading.value = false;
  document.getElementById("payMent").innerHTML = resData;
  let namevalue = document.getElementsByName("biz_content")[0].value;
  orderNum = JSON.parse(namevalue);
  localStorage.setItem("out_trade_no", orderNum.out_trade_no);
  document.forms[0].setAttribute("target", "_self"); // 当前窗口跳转
  document.forms[0].submit();
  document.getElementById("payMent").innerHTML = "";
};

const getPayResult = async () => {
  let trade_no = localStorage.getItem("out_trade_no");
  let params = {
    orderId: trade_no,
  };
  let { data } = await GetOrderInfoByTradeNo(params);
  try {
    clearInterval(setIntTime);
    if (data.order_status == 1) {
      router.push({
        path: "/register",
        query: {
          id: data.token,
        },
      });
    }
    if (data.order_status == 0 && isPay) {
      showToast("当前订单未支付");
    }
  } catch (error) {
    clearInterval(setIntTime);
  }
};

// 提交支付
let isPopup = ref(false);
const submitPay = () => {
  // payOrder()
  isPopup.value = true;
};

const is_weixn = () => {
  var ua = navigator.userAgent.toLowerCase();
  if (ua.match(/MicroMessenger/i) == "micromessenger") {
    return true;
  } else {
    return false;
  }
};

const getOpenidFn = async () => {
  //先判断有没有授权(判断地址栏code，有就-用户同意了授权，没有-没授权或者拒绝授权)
  // let str = route.query.code; //此处使用的是history路由模式，hash这么拿不到。
  let _params = queryURLParams(window.location.href);
  if (_params.code) {
    // 走后端接口(把code传给后台，让后台根据code获取openID与用户信息)
    let params = {
      code: _params.code,
    };
    // setIsPageLoading(true)
    let data = await GetOpenid(params);
    console.log(data, "a");
    if (data.openid) {
      localStorage.setItem("openid", data.openid);
      //拿到了ACCESS_TOKEN与用户openid，跳转到登录页面
      let jspParams = {
        url: window.location.href,
      };
      console.log(jspParams, "jspParams");
      try {
        let dataJsp = await getJspToken(jspParams);
        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: appid, // 必填，公众号的唯一标识
          timestamp: dataJsp.data.timestamp, // 必填，生成签名的时间戳
          nonceStr: dataJsp.data.nonceStr, // 必填，生成签名的随机串
          signature: dataJsp.data.signature, // 必填，签名
          jsApiList: ["checkJsApi", "chooseWXPay"], // 必填，需要使用的JS接口列表
        });
        wx.ready(function (res) {
          wx.checkJsApi({
            jsApiList: ["chooseWXPay"],
            success: (res) => {
              console.log("checked api:", res);
            },
            fail: (err) => {
              console.log("check api fail:", err);
            },
          });
          // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
        });
        return;
      } catch (error) {}
    } else {
    }
  }
};
const queryURLParams = (URL) => {
  let url = URL.split("?")[1];
  const urlSearchParams = new URLSearchParams(url);
  const params = Object.fromEntries(urlSearchParams.entries());
  return params;
};

const getCode = () => {
  //没授权先授权,授权后会有一个code在地址栏上
  let params = queryURLParams(window.location.href);
  if (params.code) {
    let _code = localStorage.getItem("code");
    // console.log(_code != params.code, '996')
    if (_code != params.code) {
      localStorage.setItem("code", params.code);
      getOpenidFn();
    }
    return;
  }
  // return
  window.location.href =
    "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
    appid +
    "&redirect_uri=" +
    encodeURIComponent(window.location.href) +
    "&response_type=code&connect_redirect=1&scope=snsapi_base&state=state#wechat_redirect";
};

// 微信环境获取code
if (is_weixn()) {
  getCode();
  initWeixinJSBridge();
}

let amount = ref(0);
let imageList = ref([]);
const GetFlockDetailData = async () => {
  let { data } = await GetFlockDetail({ goodsId: route.query.goodsId });
  data.comments.forEach((o) => {
    o.isLink = false;
  });
  amount.value = data.unitPrice * 100;
  imageList.value = data.image;
  state.Img01 = data.avatar;
  state.formData = data;
  userList.value = data.members.concat(userList.value);
};

let isLikes = ref(false);

const isLikesAction = () => {
  isLikes.value = !isLikes.value;
  if (isLikes.value) {
    state.formData.favorites++;
  } else {
    state.formData.favorites--;
  }
  localStorage.setItem("isLikes", isLikes.value);
};

import Clipboard from "clipboard";

const shareAction = () => {
  Clipboard.copy(
    "https://h5-dy.dearweb.cn/goodsFlockOrder?goodsId=" + route.query.goodsId
  );
  showToast("地址已复制，粘贴后发送给好友！");
};

const linkAction = (item, index) => {
  state.formData.comments[index].isLink =
    !state.formData.comments[index].isLink;
  if (state.formData.comments.isLink) {
    state.formData.comments[index].likes++;
  } else {
    state.formData.comments[index].likes--;
  }
};

onMounted(() => {
  state.anchorType[0].image = route.query.qrCode;
  state.anchorType[0].money = Number(route.query.diyPrice);
  // state.isWeixin = is_weixn()
  GetFlockDetailData();
});
</script>



<style lang="scss" scoped>
.index-container {
  width: 100vw;
  box-sizing: border-box;
  overflow: auto;
}

.goods-detail-flock-box {
  display: flex;
  justify-content: center;
  border-bottom: 2px solid #ccc;
  padding-bottom: 20px;
  background: #f2f2f2;
  .van-image {
    display: block;
    margin: 0 auto;
  }
  .goods-detail-flock {
    color: #fff;
    text-align: center;
    h3 {
      padding-top: 10px;
      font-size: 20px;
      font-weight: normal;
    }

    p {
      color: #f00;
      font-size: 16px;
    }
  }
}

.weixin-open {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(222, 222, 222);
  z-index: 999;
  display: flex;
  justify-content: center;
  align-items: flex-start;

  img {
    width: 100%;
  }
}

.pay-btn {
  margin-top: 20px;

  .pay-item {
    display: flex;
    align-items: center;
    justify-content: flex-start;
  }

  img {
    width: 24px;
    height: 24px;
    margin-right: 10px;
  }
}

:deep(.van-cell-group--inset) {
  margin: 0;
}

.verify-pay-btn {
  width: calc(100% - 30px);
  padding: 15px;
  position: absolute;
  bottom: 0;

  :deep(.van-button) {
    width: 100%;
  }
}

.tips {
  color: #fff;

  img {
    width: 100%;
  }
}

.pay-wx-main {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;

  .pay-item {
    // padding:15px;
    border-radius: 8px;
    overflow: hidden;

    h5 {
      font-size: 18px;
      margin-bottom: 10px;
    }

    img {
      width: 100%;
    }

    h5,
    p {
      text-align: center;
    }

    p {
      padding-bottom: 20px;
    }
  }
}
.default-browser {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 99999;
  background: #fff;
  img {
    width: 100%;
  }
}
.image-list {
  padding: 20px;
  background: #fff;
  .van-image {
    width: 90%;
  }
  .grid-item-img {
    p {
      white-space: nowrap; // 强制一行显示
      overflow: hidden; // 超出隐藏
      text-overflow: ellipsis; // 省略号
      text-align: center;
      width: 80%;
      height: 20px;
      line-height: 20px;
    }
  }
}
.img-item-more {
  font-size: 40px;
  text-align: center;
  line-height: 80px;
}
.van-grid-item {
  padding: 0;
  p {
    font-size: 13px;
    color: #999;
    margin-top: 5px;
  }
}
:deep(.van-grid-item__content) {
  padding: 0;
}
.image-list-item {
  border-top: 1px solid #eee;
  padding-top: 20px;
  p {
    color: #999;
    margin-bottom: 15px;
  }
}
h3 {
  font-weight: normal;
  font-size: 16px;
  margin-bottom: 15px;
}
.read {
  color: #999;
  font-size: 12px;
  margin-bottom: 20px;
}
.comment-list {
  padding: 20px;
  background: #f2f2f2;
  .comment-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 15px;
  }
  .comment-item-left {
    display: flex;
    align-items: center;
    .van-image {
      flex: none;
      margin-right: 10px;
    }
    h6 {
      font-size: 12px;
      font-weight: normal;
      color: #999;
    }
    p {
      font-size: 13px;
      color: #333;
      margin-top: 2px;
    }
  }
}

.share-btn {
  display: flex;
  justify-content: space-between;
  .share-item {
    margin-right: 5px;
  }
  .share-item-left,
  .share-item-right {
    display: flex;
    align-items: center;
    span {
      margin-left: 5px;
    }
  }
}
.footer {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100vw;
  background: #fff;
}
.submit-foote {
  width: 100%;
  box-sizing: border-box;
  padding: 15px;
}
.main-video {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
}
.grid-item-img {
  margin-bottom: 10px;
}
.comment-item-right {
  span {
    margin-left: 5px;
    color: #666;
  }
}
.van-button {
  font-size: 18px;
}
</style>
